
package com.scalar.chiptrack.operations.dataentry.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.StringTokenizer;
import java.sql.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.adaptor.AssemblyLot;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.dataentry.forms.AssemblyDataEntryForm;
import com.scalar.chiptrack.operations.process.Lot;
import com.scalar.chiptrack.operations.process.VendorLocation;
import com.scalar.chiptrack.operations.process.dao.LotDAO;
import com.scalar.chiptrack.operations.process.dao.PartNumber;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;


public final class AssemblyDataEntryAction extends ChipTrackAction {

    private static final String ACTION_NAME = "/assemblyDataEntry.do" ;
    public AssemblyDataEntryAction() {}

	public ActionForward execute (ActionMapping mapping, 
                                  ActionForm form, 
                                  HttpServletRequest request, 
                                  HttpServletResponse response) throws Exception 
	{
		HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
		
		if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY,  ACTION_NAME );
            return ( mapping.findForward ( "login" ) );
        }
        else
        {
            if ( user.isActionAllowed ( Functionality.DATA_ENTRY, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }

		ArrayList partNumberList 		= new ArrayList();
		ArrayList partNumberSelectList 	= new ArrayList();
		ArrayList vendorLocationList	= new ArrayList();
		ArrayList assemblyLocationList	= null;
		HashMap info 					= new LinkedHashMap();
		HashMap errors 					= new LinkedHashMap();
		VendorLocation vendorLocation	= null;
		AssemblyDataEntryForm assemblyDataEntryForm = (AssemblyDataEntryForm) form;
		String action 		= request.getParameter ( "action" );
		String confirm 		= request.getParameter ( "confirm" );
		String actionForward = "success";
		    
		if ( action == null )
        	action = "";
	
		if ( confirm == null )
			confirm = "";

    	partNumberList			= ProductDao.getPartNumber( "Assembly" );
		PartNumber partNumber	= null;
		
		for( int i = 0; i < partNumberList.size(); i++ )
		{
			partNumber = (PartNumber)partNumberList.get(i);
			partNumberSelectList.add( new org.apache.struts.util.LabelValueBean(partNumber.getPartNumber(), partNumber.getProcessStepId() + "$" + partNumber.getPartNumber () ) );
		}
			
		request.setAttribute( "partNumberSelectList", partNumberSelectList );
		request.setAttribute( "action", action );

		if( action.equals( "" ) )
		{
			return (mapping.findForward("success"));
		}

        String locationId		= assemblyDataEntryForm.getLocationId();
        String processStepId	= assemblyDataEntryForm.getProcessStepId();
        String quantityIn		= assemblyDataEntryForm.getQuantityIn();
        String quantityOut      = assemblyDataEntryForm.getQuantityOut();
        String dateIn			= assemblyDataEntryForm.getDateIn();
        String dateOut			= assemblyDataEntryForm.getDateOut();
        String lotId            = assemblyDataEntryForm.getLotId();
        String poNumber         = assemblyDataEntryForm.getPoNumber();

		if( action.equals( "device" ) || action.equals( "location" ) || action.equals( "lotnumber" ) || action.equals( "save" ) )
        {
            StringTokenizer st1 = new StringTokenizer( assemblyDataEntryForm.getProcessStepId(), "$" );
            String pId 			= st1.nextToken ();
            st1.nextToken ();

            assemblyLocationList = VendorDAO.getSelectedLocations( Integer.parseInt( pId ) );
            if(assemblyLocationList == null)
            {
				assemblyLocationList = new ArrayList( 0 );
            }
            
			for( int i = 0; i < assemblyLocationList.size(); i++ )
			{
                vendorLocation=(VendorLocation)assemblyLocationList.get(i);
                vendorLocation.setLocationID(vendorLocation.getLocationID());
                vendorLocation.setLocationName(vendorLocation.getLocationName());
                vendorLocationList.add( new org.apache.struts.util.LabelValueBean( vendorLocation.getLocationName(), vendorLocation.getLocationID()+ "/" + vendorLocation.getLocationName () ) );
			}
			request.setAttribute( "locationSelectList", vendorLocationList );
		}

        if ( action.equals ( "location" ) || action.equals ( "lotnumber" ) || action.equals ( "save" ) )
        {
            ArrayList list = getLotList( processStepId, locationId );
            request.setAttribute ( "lotNumbers", list );
            if ( action.equals ( "location" ) )
            {
                assemblyDataEntryForm.setLotId("0");
            }
        }

		if( action.equals( "lotnumber" ) )
		{
            if ( ( !"-1".equals ( lotId ) ) )
            {

                StringTokenizer st = new StringTokenizer ( assemblyDataEntryForm.getLotId (), "$" );
                String strLotId = st.nextToken ();
                st.nextToken ();
                st.nextToken ();

				AssemblyDataEntryForm  assyLot = LotDAO.getAssemblyLotData( strLotId );

				assemblyDataEntryForm.setLc("0".equals(assyLot.getLc())? "":assyLot.getLc());
				assemblyDataEntryForm.setDeviceType(assyLot.getDeviceType());
				assemblyDataEntryForm.setPackageType(assyLot.getPackageType());
				assemblyDataEntryForm.setPackageSize(assyLot.getPackageSize());
				assemblyDataEntryForm.setDiceInspectIn(assyLot.getDiceInspectIn());
				assemblyDataEntryForm.setDiceInspectOut(assyLot.getDiceInspectOut());
				assemblyDataEntryForm.setDiceInspectYield(assyLot.getDiceInspectYield());
				assemblyDataEntryForm.setIcFinishedIn(assyLot.getIcFinishedIn());
				assemblyDataEntryForm.setIcFinishedOut(assyLot.getIcFinishedOut());
				assemblyDataEntryForm.setIcFinishedYield(assyLot.getIcFinishedYield());
				assemblyDataEntryForm.setInvYield(assyLot.getInvYield());
				assemblyDataEntryForm.setActYield(assyLot.getActYield());
				assemblyDataEntryForm.setAsyYield(assyLot.getAsyYield());
				assemblyDataEntryForm.setQuantityIn(assyLot.getQuantityIn());
				assemblyDataEntryForm.setQuantityOut(assyLot.getQuantityOut());
				assemblyDataEntryForm.setDateIn(assyLot.getDateIn());
				assemblyDataEntryForm.setDateOut(assyLot.getDateOut());
				assemblyDataEntryForm.setVendorLotNo(assyLot.getVendorLotNo());
                assemblyDataEntryForm.setPoNumber( assyLot.getPoNumber() );
                assemblyDataEntryForm.setDateCode( assyLot.getDateCode() );
                assemblyDataEntryForm.setComments( assyLot.getComments() );
            }
            else
            {   
				StringTokenizer st1 = new StringTokenizer ( processStepId, "$" );
                String pId = st1.nextToken ();
				int psId = Integer.parseInt( pId );
				String packageType = LotDAO.getPackageTypeValue( psId );
				
				if( ( packageType != null ) && ( packageType.trim().length() > 50 ) )
				{
					String subPackageType = packageType.substring( 0, 50 );
					assemblyDataEntryForm.setPackageType( subPackageType );
				}
				else
				{
					assemblyDataEntryForm.setPackageType( packageType );
				}

                assemblyDataEntryForm.setLc("");
                assemblyDataEntryForm.setDeviceType("");
                assemblyDataEntryForm.setPackageSize("");
                assemblyDataEntryForm.setDiceInspectIn("");
                assemblyDataEntryForm.setDiceInspectOut("");
                assemblyDataEntryForm.setDiceInspectYield("");
                assemblyDataEntryForm.setIcFinishedIn("");
                assemblyDataEntryForm.setIcFinishedOut("");
                assemblyDataEntryForm.setIcFinishedYield("");
                assemblyDataEntryForm.setInvYield("");
                assemblyDataEntryForm.setActYield("");
                assemblyDataEntryForm.setAsyYield("");
                assemblyDataEntryForm.setQuantityIn("");
                assemblyDataEntryForm.setQuantityOut("");
                assemblyDataEntryForm.setDateIn(StringUtils.formatDateToString(new Date(System.currentTimeMillis()), "MM/dd/yyyy"));
                assemblyDataEntryForm.setDateOut("");
                assemblyDataEntryForm.setLotNo ( "" );
				assemblyDataEntryForm.setVendorLotNo("");
                assemblyDataEntryForm.setPoNumber( "" );
                assemblyDataEntryForm.setDateCode( "" );
                assemblyDataEntryForm.setComments( "" );
            }
            
			assemblyDataEntryForm.setPartialShippment( false );
            saveToken( request );
            request.setAttribute ( "lotnumber", "true" );
		}

        if( "allLotInfo".equals( action ) )
        {
            String lotprocessstepId = request.getParameter("ProcessStepId");
            String lotlocationId = request.getParameter("LocationId");
            String lotNo         = request.getParameter("LotNo");

            StringTokenizer st = new StringTokenizer ( lotprocessstepId, "$" );
            String pId = st.nextToken ();
            st.nextToken ();

            st = new StringTokenizer ( lotlocationId, "/" );
            String locId = st.nextToken ();
            st.nextToken ();

            ArrayList allLotsList = null;

            try
            {
                String newlotId = LotDAO.getLotId( lotNo , locId, pId  );

                if ( newlotId != null && newlotId.length() > 0 )
                {
                    allLotsList = LotDAO.getAllLotDetails( newlotId );
                }

                request.setAttribute("allLotsList", allLotsList );
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( "Error while retreiving the Lot history list", null );
            }
            return mapping.findForward( "alllotInfo" );
        }

		if( action.equals( "save" ) )
		{
            if ( quantityIn.equals ( "" ) )
            {
                quantityIn = null;
            }
            if ( dateIn.equals ( "" ) )
            {
                 dateIn = null;
            }
            if ( quantityOut.trim().equals ( "" ) )
            {
                quantityOut = null;
            }
            if ( dateOut.equals ( "" ) )
            {
                dateOut = null;
            }

            if ( ( poNumber.equals ("") || ( poNumber.trim().length()) == 0  ) )
            {
               poNumber = null;
            }
            
            if( isTokenValid( request ) )
            {
				try
				{
					//check for duplication or lot number repetition. Bhaskar on 6 December 2003
					StringTokenizer stok1 = new StringTokenizer (processStepId,"$");
					StringTokenizer stok2 = new StringTokenizer (locationId,"/");
					String procStepId 	= stok1.nextToken();
					String locatId 		= stok2.nextToken();
					String lot_ID 		= LotDAO.getLotIdInDataEntry ( null, procStepId, locatId, assemblyDataEntryForm.getLotNo() );
				
					if( lot_ID == null )
					{
						lot_ID = "";
					} 
				
					lot_ID = lot_ID.trim();
				
					if ( lotId.equals ( "-1" ) && ( !confirm.equals( "confirm" ) ) )
					{
						if ( "".equalsIgnoreCase(lot_ID)==false)
						{
							request.setAttribute( "showError", "TRUE" );
							return mapping.findForward( "success" );
						}
					}
	
					DBTransaction dbTransaction = null;
					boolean success = false;
					try
					{
						dbTransaction = DBTransaction.getInstance();
						dbTransaction.begin();
					}
					catch(Exception e){e.printStackTrace();}
	
					String strLotId = null;
					String strLotNo = null;
	            
					if ( !lotId.equals ( "-1" ) )
					{
						StringTokenizer st = new StringTokenizer ( assemblyDataEntryForm.getLotId (), "$" );
						strLotId = st.nextToken ();
						strLotNo = st.nextToken ();
						st.nextToken ();
					}
					else
					{
						strLotId = "-1";
						strLotNo = assemblyDataEntryForm.getLotNo ();
					}
	
					StringTokenizer st1 = new StringTokenizer ( processStepId, "$" );
					st1.nextToken ();
					String pNumber = st1.nextToken ();
	
					st1 = new StringTokenizer ( assemblyDataEntryForm.getLocationId (), "/" );
					st1.nextToken ();
					String vendorName = st1.nextToken ();
	
					ArrayList assemblyLotList 	= new ArrayList();
					AssemblyLot assemblyLot 	= new AssemblyLot(vendorName);
	
					assemblyLot.setDeviceName( pNumber );
					assemblyLot.setLotNumber( strLotNo );
					assemblyLot.setQtyIn( quantityIn );
					assemblyLot.setQtyOut( quantityOut );
					assemblyLot.setDateIn( dateIn );
					assemblyLot.setDateOut( dateOut );
					assemblyLot.setAsyYield( LotDAO.formatYieldToTwoDecimals ( assemblyDataEntryForm.getAsyYield() ) );
					assemblyLot.setDiceInspectIn( assemblyDataEntryForm.getDiceInspectIn() );
					assemblyLot.setDiceInspectOut( assemblyDataEntryForm.getDiceInspectOut() );
					assemblyLot.setDiceInspectYield( LotDAO.formatYieldToTwoDecimals( assemblyDataEntryForm.getDiceInspectYield() ) );
					assemblyLot.setIcFinishedIn( assemblyDataEntryForm.getIcFinishedIn() );
					assemblyLot.setIcFinishedOut( assemblyDataEntryForm.getIcFinishedOut() );
					assemblyLot.setIcFinishedYield( LotDAO.formatYieldToTwoDecimals( assemblyDataEntryForm.getIcFinishedYield() ) );
					assemblyLot.setInvYield( LotDAO.formatYieldToTwoDecimals ( assemblyDataEntryForm.getInvYield() ) );
					assemblyLot.setPackageSize( assemblyDataEntryForm.getPackageSize() );
					assemblyLot.setPackageType( assemblyDataEntryForm.getPackageType() );
					assemblyLot.setLeadCount( assemblyDataEntryForm.getLc() );
					assemblyLot.setVendorLotNumber(assemblyDataEntryForm.getVendorLotNo());
					assemblyLot.setPONumber ( poNumber );
					assemblyLot.setDateCode(assemblyDataEntryForm.getDateCode());
					assemblyLot.setComments(assemblyDataEntryForm.getComments());
                    //commented by sujan on 06th july 2005 as we don't have partial shipment
					/*assemblyLot.setPartialshipQtyIn( assemblyDataEntryForm.getPartialShipQtyIn() );
					assemblyLot.setPartialshipQtyOut( assemblyDataEntryForm.getPartialShipQtyOut() );
					assemblyLot.setPartialShipDateOut( assemblyDataEntryForm.getPartialShipDateOut() );*/
	
					assemblyLotList.add( assemblyLot );
	
					if( strLotId != null && !strLotId.equals( "-1" ) )
					{
						LotDAO.changeLotStatusToCloseByLotId(dbTransaction, strLotId); 
					}
				
					LotDAO.saveAssemblyLot( dbTransaction, assemblyLotList.iterator() );
					
					resetToken( request );
					success = true;
					actionForward = "saveSuccess";
					info.put( "Data has been updated successfully for "+ strLotNo, "");
			
					try
					{
						if( dbTransaction != null )
						{
							if( success == true )
							{
								dbTransaction.commit();	
							}
							else
							{
								dbTransaction.rollback();	
							}
						}
					}
					catch(Exception e1){ e1.printStackTrace(); }
				}
				catch( Exception e )
				{
					e.printStackTrace();
					errors.put( "Could not save the lot information ", null );
				}
			}
			else
			{
				errors.put( "Lot Information already saved", null );
				actionForward = "saveSuccess";
			}
		}
		
		if ( action.equals( "null" ) )
		{
			assemblyDataEntryForm.setProcessStepId( "0" );
			request.setAttribute( SessionKeys.INFO_MESSAGES, request.getAttribute( SessionKeys.INFO_MESSAGES ) );
			request.setAttribute( SessionKeys.ERROR_MESSAGES, request.getAttribute( SessionKeys.ERROR_MESSAGES ) );
		}
		else
		{
			request.setAttribute( SessionKeys.INFO_MESSAGES, info );
			request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
		}
		
		request.removeAttribute ( "assemblydataentryform" );
        request.setAttribute ( "assemblydataentryform", assemblyDataEntryForm );

		return ( mapping.findForward( actionForward ) ); 
	}

	private ArrayList getLotList(String processStepId, String locationId)
    {
        java.util.ArrayList list = new ArrayList();
        try
        {
            StringTokenizer st = new StringTokenizer ( processStepId, "$" );
            String pId = st.nextToken ();
            st.nextToken ();
            st = new StringTokenizer ( locationId, "/" );
            String locId = st.nextToken ();
            st.nextToken ();

            ArrayList lotNumberList = LotDAO.getRunningLotNumbersByPSTypeName ( pId, locId, "Assembly" );
            Lot lot = null;
            list = new java.util.ArrayList ();

            for ( int i = 0; i < lotNumberList.size (); i++ )
            {
                lot = ( Lot ) lotNumberList.get ( i );
                list.add ( new org.apache.struts.util.LabelValueBean ( lot.getLotNumber (), lot.getLotId () + "$" + lot.getLotNumber () + "$" + lot.getStatus () ) );
            }
        }
        catch(Exception e)
        {

        }
        return list;
    }
}